const mongoose = require('mongoose');
const shortid = require('shortid');
const moment = require('moment');


const MessageSchema = new mongoose.Schema({

    _id:{
        type:String,
        default:shortid.generate,
        unique:true,
    },
    content:{
        type:String
    },
    good_id:{
        type:String,
        ref:'Good'
    },
    target_id:{
        type:String,
        ref:'Buller'
    },
    send_id:{
        type:String,
        ref:'Buller'
    },
    type:{
        type:String,

    },
    hasRead:{
        type:Boolean,
        default:false
    },
    create_time:{
        type:Date,
        default:Date.now
    },



})
MessageSchema.statics = {
    getSellerMessages:(target_id,callback)=>{
        Message.find({'target_id':target_id,'type':'seller'}).populate('good_id').populate('send_id').sort({'create_time':-1}).then((messages)=>{

            callback(null,messages);
        }).catch((err)=>{
            callback(err);
        })
    },
    getBullerMessages:(target_id,callback)=>{
        Message.find({'target_id':target_id,'type':'buller'}).populate('good_id').populate('send_id').sort({'create_time':-1}).then((messages)=>{

            callback(null,messages);
        }).catch((err)=>{
            callback(err);
        })
    },

    getMsgById:(id,callback)=>{
        Message.findOne({'_id':id}).then((msg)=>{
            callback(null,msg);

        }).catch((err)=>{
            callback(err);
        })
    }
}

const Message = mongoose.model('message',MessageSchema);
module.exports = Message;
